package cn.kbyue.exceptiondemo.controller;

import cn.kbyue.exceptiondemo.common.CommonResponse;
import cn.kbyue.exceptiondemo.common.validate.EncryptId;
import cn.kbyue.exceptiondemo.common.validate.TravelChecks;
import cn.kbyue.exceptiondemo.common.validate.Update;
import cn.kbyue.exceptiondemo.dto.*;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.Past;
import javax.validation.groups.Default;
import java.time.LocalDate;

/**
 * get请求的参数校验需要在类上加 @Validated
 * @author kbyue
 */
@RequestMapping("/validate")
@RestController
@Validated
public class ValidateController {

    @GetMapping("{id}")
    public CommonResponse<Long> getById(@PathVariable("id") @Min(1000L) Long id) {
        return CommonResponse.success(id);
    }

    @GetMapping("/account")
    public CommonResponse<String> getByAccount(@Length(min = 6, max = 10) String account) {
        return CommonResponse.success(account);
    }

    @GetMapping("/encryptId")
    public CommonResponse<String> encryptId(@RequestParam("id") @EncryptId String id) {
        return CommonResponse.success(id);
    }

    @GetMapping("/date")
    public CommonResponse<String> date(@RequestParam("birthday") @Past LocalDate birthday) {
        return CommonResponse.success(birthday.toString());
    }

    @PostMapping("/user")
    public CommonResponse<UserDTO> validateUser(@Validated @RequestBody UserDTO userDTO) {
        return CommonResponse.success(userDTO);
    }

    @PostMapping("/enumvalidate")
    public CommonResponse<UserDTO> updateDefault(@Validated @RequestBody UserDTO userDTO) {
        return CommonResponse.success(userDTO);
    }

    /**
     * 按顺序校验字段[以分组的方式]
     */
    @PostMapping("/sequence")
    public CommonResponse<TravelBody> sequence(@Validated(TravelChecks.class) @RequestBody TravelBody travelBody) {
        return CommonResponse.success(travelBody);
    }

    /**
     * 校验字段依赖实体中其他字段
     *
     * adviceDTO
     */
    @PostMapping("/sequence/provide")
    public CommonResponse<AdviceDTO> sequenceProvide(@Validated @RequestBody AdviceDTO adviceDTO) {
        return CommonResponse.success(adviceDTO);
    }

    /**
     * 校验实体中  开始日期 小于 结束日期
     */
    @PostMapping("/sequence/date")
    public CommonResponse<DateForm> sequenceDate(@Validated @RequestBody DateForm dateForm) {
        return CommonResponse.success(dateForm);
    }

}
